<template>
  <a-card title="智能作业生成" :bordered="false">
    <a-steps :current="currentStep" class="steps-container">
      <a-step title="基础信息" />
      <a-step title="题目设置" />
      <a-step title="确认生成" />
    </a-steps>

    <div class="step-content">
      <!-- Step 1: Basic Info -->
      <div v-if="currentStep === 0" class="step-panel">
        <a-form layout="vertical">
          <a-form-item label="作业标题" required>
            <a-input v-model:value="formState.title" placeholder="例如：二次函数专项练习" />
          </a-form-item>
          <a-form-item label="学科" required>
            <a-select v-model:value="formState.subject" placeholder="请选择学科" >
              <a-select-option value="math">数学</a-select-option>
              <a-select-option value="english">英语</a-select-option>
              <a-select-option value="physics">物理</a-select-option>
              <a-select-option value="chemistry">化学</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="所属章节" required>
            <a-select
              v-model:value="formState.chapter"
              placeholder="请选择章节"
              :loading="!chapterList.length"
            >
              <a-select-option 
                v-for="chapter in chapterList" 
                :key="chapter.id" 
                :value="chapter.name"
              >
                {{ chapter.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
      </div>

      <!-- Step 2: Questions Setup -->
      <div v-if="currentStep === 1" class="step-panel">
        <a-tabs v-model:activeKey="activeQuestionTab">
          <a-tab-pane key="manual" tab="手动添加">
            <div class="question-list">
              <div
                v-for="(question, index) in formState.questions"
                :key="index"
                class="question-item"
              >
                <a-input
                  v-model:value="question.content"
                  placeholder="输入题目内容"
                  style="margin-bottom: 8px"
                />
                <a-select
                  v-model:value="question.type"
                  style="width: 120px; margin-bottom: 8px"
                  placeholder="题目类型"
                  @change="handleQuestionTypeChange(question)"
                >
                  <a-select-option value="text">问答题</a-select-option>
                  <a-select-option value="choice">选择题</a-select-option>
                </a-select>

                <!-- Options panel for choice questions -->
                <div v-if="question.type === 'choice'" class="options-panel">
                  <div v-for="(option, optIndex) in question.options" :key="optIndex" class="option-item">
                    <a-input
                      v-model:value="question.options[optIndex]"
                      :placeholder="`选项 ${String.fromCharCode(65 + optIndex)}`"
                      style="width: calc(100% - 32px)"
                    />
                    <a-button
                      type="link"
                      danger
                      @click="removeOption(index, optIndex)"
                      style="width: 32px"
                    >
                      删除
                    </a-button>
                  </div>
                  <a-button
                    @click="addOption(index)"
                    style="margin-top: 8px"
                  >
                    <template #icon><plus-outlined /></template>
                    添加选项
                  </a-button>
                </div>

                <a-form-item label="答案" style="margin-top: 8px">
                  <a-input
                    v-model:value="question.correct_answer"
                    placeholder="输入题目答案"
                  />
                </a-form-item>

                <a-space>
                  <a-input-number
                    v-model:value="question.points"
                    :min="1"
                    placeholder="分值"
                  />
                  <a-select
                    v-model:value="question.difficulty"
                    style="width: 120px"
                    placeholder="难度"
                  >
                    <a-select-option value="easy">简单</a-select-option>
                    <a-select-option value="medium">中等</a-select-option>
                    <a-select-option value="hard">困难</a-select-option>
                  </a-select>
                  <a-button
                    type="link"
                    danger
                    @click="removeQuestion(index)"
                  >
                    删除
                  </a-button>
                </a-space>
              </div>
              <a-button @click="addQuestion" style="margin-top: 16px">
                <template #icon><plus-outlined /></template>
                添加题目
              </a-button>
            </div>
          </a-tab-pane>
          <a-tab-pane key="ai" tab="AI生成" force-render>
            <div class="ai-generator">
              <a-form layout="vertical">
                <a-row :gutter="16">
                  <a-col :span="8">
                    <a-form-item label="题目数量">
                      <a-input-number
                        v-model:value="questionRequirements.count"
                        :min="1"
                        :max="20"
                      />
                    </a-form-item>
                  </a-col>
                  <a-col :span="8">
                    <a-form-item label="题目类型">
                      <a-select v-model:value="questionRequirements.type">
                        <a-select-option value="mixed">混合题型</a-select-option>
                        <a-select-option value="choice">选择题</a-select-option>
                        <a-select-option value="fill">填空题</a-select-option>
                        <a-select-option value="calculation">计算题</a-select-option>
                      </a-select>
                </a-form-item>
                  </a-col>
                  <a-col :span="8">
                    <a-form-item label="学习目标阶段">
                      <a-select v-model:value="questionRequirements.learningPhase">
                        <a-select-option value="preparation">准备阶段</a-select-option>
                        <a-select-option value="cognitive">认知阶段</a-select-option>
                        <a-select-option value="comprehension">理解阶段</a-select-option>
                        <a-select-option value="application">应用阶段</a-select-option>
                        <a-select-option value="consolidation">巩固阶段</a-select-option>
                        <a-select-option value="evaluation">评估阶段</a-select-option>
                        <a-select-option value="innovation">创新迁移阶段</a-select-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                </a-row>
                <a-form-item label="知识点">
                  <a-input
                    v-model:value="questionRequirements.knowledgePoints"
                    placeholder="例如：三角函数、导数应用等"
                  />
                </a-form-item>
                <a-form-item label="生成要求">
                  <a-textarea
                    v-model:value="aiPrompt"
                    placeholder="例如：需要包含实际应用场景的题目"
                    :rows="3"
                  />
                </a-form-item>
                <a-form-item>
                  <a-space>
                    <a-button
                    type="primary"
                    @click="generateQuestions"
                    :loading="aiGenerating"
                    >
                    <template #icon><robot-outlined /></template>
                    生成题目
                    </a-button>
                    <a-button @click="applyGeneratedQuestions" :disabled="!generatedQuestions.length">
                      应用题目
                    </a-button>
                  </a-space>
                </a-form-item>
              </a-form>
              <div v-if="generatedQuestions.length" class="generated-questions">
                <h4>生成的题目：</h4>
                <a-list :data-source="generatedQuestions" :grid="{ gutter: 16, column: 1 }">
                  <template #renderItem="{ item }">
                    <a-list-item>
                      <a-card>
                        <p>{{ item.question_stem || item.content }}</p>
                        <div v-if="item.options" class="question-options">
                          <p v-for="(option, idx) in item.options" :key="idx">
                            {{ option }}
                          </p>
                        </div>
                        <p class="question-meta">
                          答案: {{ item.correct_answer || '未提供' }} |
                          难度: {{ formatDifficulty(item) }} |
                          分值: {{ item.points || item.tags?.points || 5 }}
                        </p>
                      </a-card>
                    </a-list-item>
                  </template>
                </a-list>
              </div>
            </div>
          </a-tab-pane>
        </a-tabs>
    </div>

      <!-- Step 3: Review & Assign -->
      <div v-if="currentStep === 2" class="step-panel">
        <div class="review-panel">
          <h3>题目预览</h3>
          <a-descriptions bordered :column="1">
            <a-descriptions-item label="作业标题">
              {{ formState.title }}
            </a-descriptions-item>
            <a-descriptions-item label="题目数量">
              {{ formState.questions.length }}题
            </a-descriptions-item>
            <a-descriptions-item label="总分">
              {{ calculateTotalPoints() }}分
            </a-descriptions-item>
          </a-descriptions>

          <div class="question-review" style="margin-top: 24px">
            <h4>题目列表</h4>
            <a-list
              :data-source="formState.questions"
              :grid="{ gutter: 16, column: 1 }"
            >
              <template #renderItem="{ item, index }">
                <a-list-item>
                  <a-card>
                    <p><strong>题目 {{ index + 1 }}:</strong> {{ item.content }}</p>
                    <p class="question-meta">
                      难度: {{ getDifficultyName(item.difficulty) }} | 分值: {{ item.points }}分
                    </p>
                  </a-card>
                </a-list-item>
              </template>
            </a-list>
          </div>
        </div>
      </div>
    </div>

    <div class="step-actions">
      <a-button v-if="currentStep > 0" @click="prevStep">上一步</a-button>
      <a-button
        v-if="currentStep < 2"
        type="primary"
        @click="nextStep"
        style="margin-left: 8px"
      >
        下一步
      </a-button>
      <a-button
        v-if="currentStep === 2"
        type="primary"
        @click="assignHomework"
        style="margin-left: 8px"
        :loading="assigning"
      >
        确认布置
      </a-button>
    </div>
  </a-card>
</template>

<script>
import { PlusOutlined, RobotOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import axios from "axios"

export default {
  name: 'AssignHomework',
  components: {
    PlusOutlined,
    RobotOutlined,
  },
  data() {
    return {
      chapterList: [],
      apiConfig: {
        baseUrl: 'http://localhost:8000',
        apiUrl: 'http://121.40.242.43/v1',
        endpoints: {
          updates: '/api/updates/'
        }
      },
      getLearningPhaseName(phase) {
      const phaseMap = {
        'preparation': '准备阶段',
        'cognitive': '认知阶段',
        'comprehension': '理解阶段',
        'application': '应用阶段',
        'consolidation': '巩固阶段',
        'evaluation': '评估阶段',
        'innovation': '创新迁移阶段'
      };
      return phaseMap[phase] || '认知阶段';
    },
      questionRequirements: {
        type: 'mixed',
        difficulty: 'medium',
        knowledgePoints: '',
        count: 5,
        phase: '3',
        learningPhase: 'cognitive'
      },
      currentStep: 0,
      activeQuestionTab: 'manual',
      formState: {
        title: '',
        subject: '',
        chapter: null,
        classes: [],  //
        questions: [
          {
            content: '',
            points: 5,
            difficulty: 'medium',
          },
        ],
      },
      classList: [
        { id: 'class1', name: '高一(1)班' },
        { id: 'class2', name: '高一(2)班' },
        { id: 'class3', name: '高一(3)班' },
      ],
      aiPrompt: '',
      aiGenerating: false,
      generatedQuestions: [],
      assigning: false,
      aiApiKeys: {
      generation: null
      },
      apiKeyLoading: false
    }
      },
  created() {
  this.fetchChapters();  // 组件创建时加载章节
  this.fetchApiKeys();
  },
  methods: {
    async recordUpdate(action, target, details = '') {
      try {
        const message = `${target}: ${details}`;
        await axios.post(this.apiConfig.baseUrl + this.apiConfig.endpoints.updates, {
          message,
        });
      } catch (error) {
        console.error('记录更新日志失败:', error);
      }
    },
    async fetchApiKeys() {
      this.apiKeyLoading = true;
      try {
        const response = await axios.get('http://127.0.0.1:8000/api/knowledge-base-keys/');
        if (response.status === 200 && response.data) {
          const keys = response.data;
          this.aiApiKeys.generation = keys.find(k => k.name === '题目一键生成助手')?.api_key || null;
        }
      } catch (error) {
        console.error('Failed to fetch API keys:', error);
      } finally {
        this.apiKeyLoading = false;
      }
    },
    async fetchChapters() {
      try {
        const res = await fetch('http://127.0.0.1:8000/api/chapters/', {
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
          }
        });

        if (!res.ok) {
          const error = await res.text();
          throw new Error(`请求失败: ${res.status} - ${error}`);
        }

        const data = await res.json();
        this.chapterList = Array.isArray(data) ? data : data.results || [];
      } catch (error) {
        console.error('API请求错误:', error);
        message.error('获取章节失败: ' + error.message);
      }
    },
    formatDifficulty(question) {
    const level = question.difficulty_level ?? question.difficulty ?? question.tags?.difficulty;
    
    if (typeof level === 'number') {
      if (level <= 2) return '简单';
      if (level <= 4) return '中等';
      return '困难';
    }
    
    if (typeof level === 'string') {
      const lowerLevel = level.toLowerCase();
      const map = {
        'easy': '简单',
        'medium': '中等', 
        'hard': '困难',
        '简单': '简单',
        '中等': '中等',
        '困难': '困难'
      };
      return map[lowerLevel] || '未知';
    }
    
    return '未设置';
  },
    nextStep() {
      if (this.validateCurrentStep()) {
        this.currentStep++
        }
    },
    prevStep() {
      this.currentStep--
    },
    validateCurrentStep() {
      if (this.currentStep === 0) {
        if (!this.formState.title) {
          message.error('请输入作业标题')
          return false
        }
        if (!this.formState.subject) {
          message.error('请选择学科')
          return false
        }
      } else if (this.currentStep === 1) {
        if (this.formState.questions.length === 0) {
          message.error('请至少添加一个题目')
          return false
        }
        for (const q of this.formState.questions) {
          if (!q.content) {
            message.error('请填写所有题目内容')
            return false
          }
        }
      }
      return true
    },
    removeQuestion(index) {
    this.formState.questions.splice(index, 1)
    if (this.formState.questions.length === 0) {
      this.addQuestion()
    }
  },
    addQuestion() {
    this.formState.questions.push({
      content: '',
      type: 'text',
      points: 5,
      difficulty: 'medium',
      options: []
    })
  },

  handleQuestionTypeChange(question) {
    if (question.type === 'choice' && !question.options) {
      this.$set(question, 'options', ['', ''])
    }
  },

  addOption(questionIndex) {
    if (!this.formState.questions[questionIndex].options) {
      this.$set(this.formState.questions[questionIndex], 'options', [])
    }
    this.formState.questions[questionIndex].options.push('')
  },

  removeOption(questionIndex, optionIndex) {
    const question = this.formState.questions[questionIndex]
    if (question.options && question.options.length > 2) {
      question.options.splice(optionIndex, 1)
    } else {
      message.warning('选择题至少需要2个选项')
    }
  },
  async generateQuestions() {
    if (!this.aiApiKeys.generation) {
      message.error('题目一键生成助手API Key未配置');
      return;
    }
    this.aiGenerating = true;
    this.generatedQuestions = [];
    
    try {
        const prompt = `请生成${this.questionRequirements.count}道${this.getSubjectName(this.formState.subject)}题目，要求：
- 学习目标阶段：${this.getLearningPhaseName(this.questionRequirements.learningPhase)}
- 题目类型：${this.getQuestionTypeName(this.questionRequirements.type)}
- 知识点：${this.questionRequirements.knowledgePoints || '不限'}
- 其他要求：${this.aiPrompt || '无'}
请合理分配难度
请返回严格JSON格式的题目数组，包含以下字段：
[
{
  "question_stem": "题目内容",
  "options": ["A:选项", "B:选项", "C:选项", "D:选项"],
  "correct_answer": "正确答案", // 一定要提供答案
  "difficulty_level": 3, // 1-5
  "phase": 1, // 1-7
  "tags": {
    "points": 5, // 分值
    "knowledgePoints": "相关知识点",
    "questionType": "题目类型"
  }
}
]`;


      const response = await fetch(this.apiConfig.apiUrl + '/chat-messages', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${this.aiApiKeys.generation}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          inputs: {},
          query: prompt,
          response_mode: "streaming",
          user: "teacher-assistant"
        })
      });

      let fullAnswer = '';
      const reader = response.body.getReader();
      const decoder = new TextDecoder();

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        const chunk = decoder.decode(value);
        const lines = chunk.split('\n').filter(line => line.trim());

        for (const line of lines) {
          if (line.startsWith('data: ')) {
            const data = JSON.parse(line.substring(6));

            if (data.event === 'message') {
              fullAnswer += data.answer;
            }
            else if (data.event === 'message_end') {
              try {
                const cleanAnswer = fullAnswer.replace(/```json|```/g, '').trim();
                const parsed = JSON.parse(cleanAnswer);
                this.generatedQuestions = Array.isArray(parsed) ? parsed : parsed.questions || [];
              } catch (e) {
                message.warning('解析题目失败，请检查AI返回格式');
                console.error('解析错误:', e, '原始内容:', fullAnswer);
              }
            }
          }
        }
      }
    } catch (error) {
      message.error('题目生成失败: ' + error.message);
    } finally {
      this.aiGenerating = false;
    }
  },
  getQuestionTypeName(type) {
    const map = {
      mixed: '混合题型',
      choice: '选择题',
      fill: '填空题',
      calculation: '计算题'
    };
    return map[type] || type;
  },
  applyGeneratedQuestions() {
    // 先过滤掉空的题目
    this.formState.questions = this.formState.questions.filter(
      q => q.content && q.content.trim() !== ''
    );
    
    // 添加生成的题目
    this.formState.questions = [
      ...this.formState.questions,
      ...this.generatedQuestions.map(q => ({
        content: q.question_stem,
        type: this.mapQuestionType(q.tags?.questionType || q.type),
        points: q.tags?.points || 5,
        difficulty: this.mapDifficulty(q.difficulty_level || q.difficulty),
        options: q.options,
        correct_answer: q.correct_answer,
        knowledgePoints: q.tags?.knowledgePoints || ''
      }))
    ];
    
    this.generatedQuestions = [];
    message.success('已应用生成的题目');
  },

  mapDifficulty(level) {
    if (typeof level === 'number') {
      if (level <= 2) return 'easy'
      if (level <= 4) return 'medium'
      return 'hard'
    }
    // Handle string difficulty levels from AI
    if (typeof level === 'string') {
      level = level.toLowerCase()
      if (['easy', 'simple'].includes(level)) return 'easy'
      if (['medium', 'moderate'].includes(level)) return 'medium'
      if (['hard', 'difficult'].includes(level)) return 'hard'
    }
    return 'medium' // default
  },

  mapQuestionType(type) {
    if (!type) return 'text'
    const typeMap = {
      'choice': 'choice',
      '选择题': 'choice',
      'fill': 'text',
      '填空题': 'text',
      'calculation': 'text',
      '计算题': 'text',
      'mixed': 'text'
    }
    return typeMap[type.toLowerCase()] || 'text'
  },
 
    analyzeHomework() {
      this.getAISuggestions();
    },
  resetForm() {
    this.currentStep = 0
    this.formState = {
      title: '',
      subject: '',
      chapter:null,
      questions: [
        {
          content: '',
          points: 5,
          difficulty: 'medium',
        },
      ],
    }
  },
  calculateTotalPoints() {
    return this.formState.questions.reduce((sum, q) => sum + q.points, 0)
  },
  getSubjectName(subject) {
    const map = {
      math: '数学',
      english: '英语',
      physics: '物理',
      chemistry: '化学',
    }
    return map[subject] || subject
  },
  getClassName(classId) {
    const cls = this.classList.find((c) => c.id === classId)
    return cls ? cls.name : classId
  },
  getDifficultyName(difficulty) {
    const map = {
      easy: '简单',
      medium: '中等',
      hard: '困难',
    }
    return map[difficulty] || difficulty
  },
  async assignHomework() {
    this.assigning = true;
    
    try {
      const selectedChapter = this.chapterList.find(
        c => c.name === this.formState.chapter
      );
      if (!selectedChapter) throw new Error('请选择有效章节');

      const questionsData = this.formState.questions.map(q => ({
        question_stem: q.content,
        options: q.options || [],
        correct_answer: q.correct_answer || '无',
        difficulty_level: this.mapDifficultyToNumber(q.difficulty),
        phase: this.questionRequirements.phase || 1,
        tags: {
          type: q.type,
          points: q.points,
          knowledgePoints:q.knowledgePoints
        },
        chapter: selectedChapter.id
      }));

      const res = await fetch('http://127.0.0.1:8000/api/question-lists/', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(questionsData)
      });
      await this.recordUpdate(
          'add',
          'AI生成作业',
          `标题: ${this.formState.title}, ` +
          `章节: ${selectedChapter.name}, ` +
          `题目: ${this.formState.questions.length}题`
        );
      if (!res.ok) {
        const error = await res.json();
        throw new Error(error.detail || JSON.stringify(error));
      }
      
      message.success(`成功保存${this.formState.questions.length}道题目`);
      this.resetForm();
    } catch (error) {
      message.error(`保存失败: ${error.message}`);
    } finally {
      this.assigning = false;
    }
  },

  mapDifficultyToNumber(difficulty) {
    const map = { easy: 1, medium: 3, hard: 5 };
    return map[difficulty] || 3;
  },
  formatDateTime(date) {
    return date ? date.format('YYYY-MM-DD HH:mm') : ''
  },
  },

}
</script>

<style scoped>
.steps-container {
  margin-bottom: 32px;
  max-width: 800px;
}

.step-panel {
  min-height: 400px;
  padding: 0 16px;
}

.step-actions {
  margin-top: 24px;
  text-align: right;
}

.question-item {
  margin-bottom: 16px;
  padding: 12px;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
}

.question-meta {
  color: #888;
  font-size: 0.9em;
  margin-top: 8px;
}

.ai-generator {
  margin-top: 16px;
}

.generated-questions {
  margin-top: 16px;
  max-height: 300px;
  overflow-y: auto;
}

.ai-optimization {
  padding: 16px;
}

.difficulty-analysis {
  margin: 16px 0;
}

.difficulty-analysis .ant-progress {
  margin-bottom: 8px;
}

.review-panel {
  padding: 16px;
}
.options-panel {
  margin: 8px 0;
  padding: 8px;
  background: #f5f5f5;
  border-radius: 4px;
}

.option-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}
</style>








      question.options.splice(optionIndex,


